package com.mzba.easy.weibo.ui;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.mzba.easy.weibo.BasicActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.db.CommentEntry;
import com.mzba.easy.weibo.db.EmotionField;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.BasicUIEvent;
import com.mzba.easy.weibo.util.UICore;
import com.mzba.easy.weibo.util.WeiboManager;
import com.mzba.easy.weibo.widget.CustomTextView;
import com.mzba.easy.weibo.widget.RemoteImageView;
/**
 * 
 * @author 06peng
 *
 */
public class CommentTimelineAdapter extends BaseAdapter implements Callback, BasicUIEvent {
	
	private List<CommentEntry> entries;
	private Context context;
	private ListView listView;
	
	private LinearLayout preLayout;
	
	private LayoutParams params;
	private PopupWindow pop;
	private String commentId;
	
	private Handler handler;
	private WeiboManager weiboManager;
	private boolean isRetweet = false;
	private EditText currentEdit;
	
	public static final int DESTROYDIALOG = 0x00000101;
	private static final int reply_comment = 0x00000102;
	private static final int reply_comment_error = 0x00000103;
	private static final int delete = 0x00000104;
	private static final int delete_error = 0x000005;
	private View popViewToShow;
	
	public static class ViewHolder {
		RemoteImageView avatarView;
		CustomTextView textView;
		TextView replyTextView;
		TextView sourceView;
		TextView deleteView;
		TextView replyView;
		LinearLayout replyLayout;
		LinearLayout bodyLayout;
		
		ImageButton emotionView;
		ImageView commentRetweetView;
		LinearLayout retweetSelectLayout;
		Button commentButtonView;
		EditText editView;
	}

	
	public CommentTimelineAdapter(Context context, List<CommentEntry> entries, ListView listView) {
		this.entries = entries;
		this.context = context;
		this.listView = listView;
		handler = new Handler(this);
		weiboManager = new WeiboManager(context);
		params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.leftMargin = 35;
		
		View view = LayoutInflater.from(context).inflate(R.layout.emotion_gridview, null);
		GridView gridView = (GridView) view.findViewById(R.id.emotion_gridview);
		GridViewAdapter gridAdapter = new GridViewAdapter(context);
		gridView.setAdapter(gridAdapter);
		pop = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
		ColorDrawable dw = new ColorDrawable(-00000);
		pop.setBackgroundDrawable(dw);
		pop.update();
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				try {
					pop.dismiss();
					EmotionField filed = AppContext.getInstance().getEmotionFields().get(arg2);
					if (currentEdit != null) {
						currentEdit.append(filed.getPhrase());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		popViewToShow = LayoutInflater.from(context).inflate(R.layout.comments_timeline_item, null);
	}

	@Override
	public int getCount() {
		return entries.size();
	}

	@Override
	public Object getItem(int position) {
		return entries.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
//		if (convertView == null) {
			convertView = LayoutInflater.from(context).inflate(R.layout.comments_timeline_item, null);
			holder = new ViewHolder();
			holder.avatarView = (RemoteImageView) convertView.findViewById(R.id.iv_author_photo);
			holder.textView = (CustomTextView) convertView.findViewById(R.id.comments_timeline_text);
			holder.sourceView = (TextView) convertView.findViewById(R.id.commemnts_timeline_from);
			holder.deleteView = (TextView) convertView.findViewById(R.id.comments_timeline_delete);
			holder.replyView = (TextView) convertView.findViewById(R.id.comments_timeline_reply);
			holder.replyTextView = (TextView) convertView.findViewById(R.id.comments_timeline_reply_text);
			holder.replyLayout = (LinearLayout) convertView.findViewById(R.id.comments_timeline_reply_layout);
			holder.bodyLayout = (LinearLayout) convertView.findViewById(R.id.comments_timeline_bodylayout);
			
			holder.editView = (EditText) convertView.findViewById(R.id.timeline_comment_edit);
			holder.emotionView = (ImageButton) convertView.findViewById(R.id.timeline_comment_emotion);
			holder.commentRetweetView = (ImageView) convertView.findViewById(R.id.timeline_comment_retweet_select);
			holder.retweetSelectLayout = (LinearLayout) convertView.findViewById(R.id.timeline_comment_retweet_select_layout);
			holder.commentButtonView = (Button) convertView.findViewById(R.id.timeline_comment_comment);
			
			convertView.setTag(holder);
//		} else {
//			holder = (ViewHolder) convertView.getTag();
//		}
		final CommentEntry entry = entries.get(position);
		if (entry != null) {
			
		}
		holder.avatarView.setDefaultImage(R.drawable.avatar_default_big);
		holder.avatarView.setImageUrl(entry.getUser().getProfile_image_url(), AppContext.UNAVAILABLE, position, listView);
		String username = entry.getUser().getScreen_name() + ":" + "&nbsp;";
		holder.textView.setText(entry.getText(), username, AppContext.getInstance().getFaceMap());
		holder.sourceView.setText(Html.fromHtml("来自" + entry.getSource()));
		if (AppContext.getInstance().getUid().equals(entry.getUser().getId())) {
			holder.replyLayout.setVisibility(View.GONE);
		} else {
			holder.replyLayout.setVisibility(View.VISIBLE);
		}
		if (entry.getReply_comment() != null) {
			holder.replyTextView.setText(Html.fromHtml("回复我的评论:&nbsp;" + "<font color=#419AD9>" + entry.getReply_comment().getText() + "</font>"));
		} else {
			String user = null;
			if (entry.getStatus().getUser().getId().equals(AppContext.getInstance().getUid())) {
				user = "我";
			} else {
				user = "<font color=#419AD9>" + entry.getStatus().getUser().getScreen_name() + "</font>";
			}
			holder.replyTextView.setText(Html.fromHtml("评论"+user+"的微博:&nbsp;" + "<font color=#419AD9>" + entry.getStatus().getText() + "</font>"));
		}
		holder.replyView.setTag(holder.bodyLayout);
		if (entry.isSelected()) {
			holder.bodyLayout.setVisibility(View.VISIBLE);
		}
		if (preLayout != null) {
			preLayout.setVisibility(View.GONE);
		}
		
		holder.commentButtonView.setTag(holder.editView);
		holder.commentButtonView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				EditText editView = (EditText) v.getTag();
				String content = editView.getText().toString().trim();
				Object[] objs = new Object[4];
				objs[0] = content;
				objs[1] = entry.getStatus().getId();
				objs[2] = entry.getId();
				objs[3] = isRetweet == true ? 1 : 0;
				UICore.eventTask(CommentTimelineAdapter.this, (BasicActivity) context, reply_comment, "", objs); 
			}
		});
		
		holder.bodyLayout.setTag(holder.editView);
		holder.replyView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, NewsActivity.class);
				intent.putExtra("id", entry.getStatus().getId());
				intent.putExtra("reid", entry.getId());
				intent.putExtra(AppContext.NEWTYPE, 3);
				context.startActivity(intent);
//				LinearLayout bodyLayout = (LinearLayout) v.getTag();
//				EditText editView = (EditText) bodyLayout.getTag();
//				if (bodyLayout.getVisibility() == View.VISIBLE) {
//					bodyLayout.setVisibility(View.GONE);
//					entry.setSelected(false);
//					currentEdit = null;
//				} else {
//					bodyLayout.setVisibility(View.VISIBLE);
//					entry.setSelected(true);
//					editView.setText("回复@" + entry.getUser().getScreen_name() + ":");
//					editView.setFocusable(true);
//					editView.setFocusableInTouchMode(true);
//					currentEdit = editView;
//				}
//				preLayout = bodyLayout;
			}
		});
		
		holder.deleteView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				commentId = entry.getId();
				((BasicActivity) context).setSysMes("确定要删除该评论吗？", delete);
			}
		});
		
		holder.emotionView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (!pop.isShowing()) {
					pop.showAtLocation(popViewToShow, Gravity.BOTTOM, 0, 0);
				} else {
					pop.dismiss();
				}
			}
		});
		
		holder.retweetSelectLayout.setTag(holder.commentRetweetView);
		holder.retweetSelectLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ImageView retweetView = (ImageView) v.getTag();
				if (isRetweet) {
					isRetweet = false;
					retweetView.setBackgroundResource(R.drawable.btn_comment_sametime_unselect);
				} else {
					isRetweet = true;
					retweetView.setBackgroundResource(R.drawable.btn_comment_sametime_select);
				}
			}
		});
		return convertView;
	}
	
	@Override
	public void execute(int mes, Object obj) {
		try {
			switch (mes) {
			case reply_comment:
				Object[] objs2 = (Object[]) obj;
				CommentEntry commentEntry2 = weiboManager.replayCommemnt(objs2[0].toString(), objs2[1].toString(), objs2[2].toString(),
						Integer.parseInt(objs2[3].toString()));
				if (commentEntry2 != null) {
					handler.sendEmptyMessage(reply_comment);
				} else {
					handler.sendEmptyMessage(reply_comment_error);
				}
				break;
			case delete:
				CommentEntry entry3 = weiboManager.destroyComment(commentId);
				if (entry3 != null) {
					handler.sendEmptyMessage(delete);
				} else {
					handler.sendEmptyMessage(delete_error);
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case reply_comment:
			((BasicActivity) context).onToast("评论成功");
			break;
		case reply_comment_error:
			((BasicActivity) context).onToast("评论失败");
			break;
		case delete:
			((BasicActivity) context).onToast("删除成功");
			break;
		case delete_error:
			((BasicActivity) context).onToast("删除失败");
			break;
		default:
			break;
		}
		return false;
	}

}
